<?php

class Crud_Form_Element_Column_Filev2 extends Crud_Form_Element_Column
{
	/**
	 * Create element.
	 * 
	 * @return void
	 */
	public function init()
	{
		$element = $this->getElement();
		$column = $this->getColumn();
		$element->isReallyRequired = !$column->isNull();
		
		$adapter = new File_Transfer_Http();
		$adapter->setDestination(Config::getInstance()->file_transfer->destination);
		$element->setTransferAdapter($adapter);
	}
	
	/**
	 * Return element class.
	 * 
	 * @return string
	 */
	protected function _getElementClass()
	{
		return 'Crud_ZendFormElement_File';
	}
	
	/**
	 * Set value for given row.
	 * 
	 * @param Crud_Section_Row
	 * @param mixed $value
	 * @return void
	 */
	public function setRowValue(Crud_Section_Row $row, $value)
	{
		$element = $this->getElement();
		
		if (!$element->isUploaded()) {
			return;
		}
		
		if (!$element->isReceived()) {
			$element->receive();
		}

		$filename = $element->getFileName(null, false);
		$directory = $element->getDestination();
		$id = $this->getUploadedIdFrimImage($row->getRow(),$directory,$filename);
		parent::setRowValue($row, $id);
	}
	
	public function getUploadedIdFrimImage(Db_Row $row, $directory,$filename){
		
		$config =  Config::getInstance();
		$force = 0;
		if(isset($config->file_transfer->force))
			$force = $config->file_transfer->force;
		
		$table = $row->getTable();
		$column = $this->getColumn()->getKey();
		return Image::getInstance()->uploadOriginal($directory.DIRECTORY_SEPARATOR.$filename, $table->getName(), $column, $force);
	}
}